﻿var $ = layui.$;

//渲染表格数据
layui.use(['form', 'table', 'laypage', 'jquery', 'layer', 'laydate'], function () {
    var laydate = layui.laydate;
    var form = layui.form;
    var table = layui.table;
    var laypage = layui.laypage;
    var layer = layui.layer;
    // 渲染
    laydate.render({
        elem: '#sDeliveryDate'
    });
    laydate.render({
        elem: '#eDeliveryDate'
    });
    var pageSize = 15; // 每页显示条数

    //获取列表
    function getListData(pageIndex) {
        //查询条件
        var sDeliveryDate = $("#sDeliveryDate").val();
        var eDeliveryDate = $("#eDeliveryDate").val();
        var motherEarHorn = $("#motherEarHorn").val();
        var currentBuilding = $("#currentBuilding").val();
        var transferBuilding = $("#transferBuilding").val();
        var broodNumber = $("#broodNumber").val();
        var personCharge = $("#personCharge").val();

        //ajax后台交互
        $.ajax({
            url: 'http://10.31.60.18:8000/ProduceGetRout/api/SeedBirthRead/GetSeedBirthList',
            type: 'get',
            dataType: 'json',
            //参数
            data: {
                pageIndex: pageIndex,
                pageSize: pageSize,
                sDeliveryDate: sDeliveryDate || "",
                eDeliveryDate: eDeliveryDate || "",
                motherEarHorn: motherEarHorn || "",
                currentBuilding: currentBuilding || "",
                transferBuilding: transferBuilding || "",
                broodNumber: broodNumber || "",
                personCharge: personCharge || "",
            },
            success: function (data) {
                table.render({
                    //挂载的表格id
                    elem: '#ID-table-demo-setRowChecked',
                    cols: [[
                        { type: 'checkbox', width: 60, fixed: 'left', unresize: true, align: 'center' },
                        { type: 'numbers', title: '序号', width: 60, fixed: 'center', unresize: true, align: 'center' },
                        { field: 'motherEarHorn', width: 180, title: '种母耳号', sort: true, templet: addLink },
                        { field: 'deliveryDate', title: '分娩日期', width: 120, align: 'center', templet: function (data) { return data.deliveryDate.substring(0, 10) } },
                        { field: 'gestationDays', title: '妊娠天数', width: 120, align: 'center' },
                        { field: 'difficultyOfDelivery', title: '分娩难易', width: 120, align: 'center' },
                        { field: 'motherhood', title: '母性', width: 120, align: 'center' },
                        { field: 'lactation', title: '泌乳', width: 120, align: 'center' },
                        { field: 'mastitis', title: '乳房炎', width: 120, align: 'center' },
                        { field: 'totalNumberLambsLitter', title: '窝总羔数', width: 120, align: 'center' },
                        { field: 'litterTotalWeight', title: '窝总重(公斤)', width: 120, align: 'center' },
                        { field: 'liveLambCount', title: '活羔总数', width: 120, align: 'center' },
                        { field: 'totalWeightLiveLamb', title: '活羔总重', width: 120, align: 'center' },
                        { field: 'allLiveLambsWeigh', title: '活羔均重', width: 120, align: 'center' },
                        { field: 'deadLambCount', title: '死羔总数', width: 120, align: 'center' },
                        { field: 'totalDeadLambWeight', title: '死羔总重', width: 120, align: 'center' },
                        { field: 'allDeadLambsWeigh', title: '死羔均重', width: 120, align: 'center' },
                        { field: 'fatSheepLot', title: '肥羊批次', width: 120, align: 'center' },
                        { field: 'healthyNumber', title: '健羔数', width: 120, align: 'center' },
                        { field: 'weakLambNumber', title: '弱羔数', width: 120, align: 'center' },
                        { field: 'deformityNumber', title: '畸形数', width: 120, align: 'center' },
                        { field: 'numberOfSTillbirths', title: '死胎数', width: 120, align: 'center' },
                        { field: 'mummyNumber', title: '木乃伊数', width: 120, align: 'center' },
                        { field: 'broodNumber', title: '窝号', width: 120, align: 'center' },
                        { field: 'sex', title: '性别', width: 120, align: 'center', templet: function (data) { return data.sex == true ? "公" : "母" } },
                        { field: 'currentBuilding', title: '当前栋舍', width: 120, align: 'center' },
                        { field: 'currentField', title: '当前栏位', width: 120, align: 'center' },
                        { field: 'transferBuilding', title: '转入栋舍', width: 120, align: 'center' },
                        { field: 'driveField', title: '转入栏位', width: 120, align: 'center' },
                        { field: 'personCharge', title: '负责人', width: 120, align: 'center' },
                        { field: 'createBy', title: '创建人', width: 120, align: 'center' },
                        { field: 'createDate', title: '创建时间', width: 120, align: 'center', templet: function (data) { return data.createDate.substring(0, 10) } },
                        { field: 'updateBy', title: '修改人', width: 120, align: 'center' },
                        { field: 'updateDate', title: '修改时间', width: 120, align: 'center', templet: function (data) { return data.updateDate == null ? "" : data.updateDate.substring(0, 10) } },
                        { field: 'auditor', title: '审核人', width: 120, align: 'center' },
                        { field: 'auditTime', title: '审核时间', width: 120, align: 'center', templet: function (data) { return data.auditTime == null ? "" : data.auditTime.substring(0, 10) } },
                        { title: '操作', width: 120, align: 'center', templet: '#barDemo', fixed: 'right', unresize: true },
                    ]],
                    data: data.data.datas
                });

                //分页
                laypage.render({
                    //挂载的分页id
                    elem: 'pagesbox',
                    count: data.data.totalCount,
                    limit: pageSize,
                    limits: [15, 20, 30],
                    curr: pageIndex,
                    layout: ['count', 'prev', 'page', 'next', 'limit', 'skip'],
                    jump: function (obj, first) {
                        if (!first) {
                            pageSize = obj.limit;
                            getListData(obj.curr);
                        }
                    }
                });
            }
        })

        $(document).ready(function () {
            $.ajax({
                url: 'http://10.31.60.18:8000/AuthorizationGetRout/api/Cottage/CootList',
                type: 'get',
                dataType: 'json',
                success: function (res) {
                    data = res; // 直接使用返回的数据
                    var select = $('#currentBuilding');
                    $.each(data, function (index, item) {
                        // 使用正确的字段添加选项到下拉框中
                        var option = $('<option>').val(item.name).text(item.name);
                        select.append(option);
                    });
                    // 手动触发 layui 组件的渲染
                    layui.form.render('select');
                },
                error: function () {
                    // 处理 AJAX 请求失败的情况
                    console.error('Failed to fetch data for dropdown.');
                }
            });
        });

        $(document).ready(function () {
            $.ajax({
                url: 'http://10.31.60.18:8000/AuthorizationGetRout/api/Cottage/CootList',
                type: 'get',
                dataType: 'json',
                success: function (res) {
                    data = res; // 直接使用返回的数据
                    var select = $('#transferBuilding');
                    $.each(data, function (index, item) {
                        // 使用正确的字段添加选项到下拉框中
                        var option = $('<option>').val(item.name).text(item.name);
                        select.append(option);
                    });
                    // 手动触发 layui 组件的渲染
                    layui.form.render('select');
                },
                error: function () {
                    // 处理 AJAX 请求失败的情况
                    console.error('Failed to fetch data for dropdown.');
                }
            });
        });

        $('#searchBtn').on('click', function () {
            getListData(1);
        });
    }

    // 单删除
    function deleteData(id) {
        $.ajax({
            url: `http://10.31.60.18:8000/ProduceSetRout/api/SeedBirth/RemoveSeedBirth?id=${id}`,
            type: 'delete',
            success: function (data) {
                if (data.code == 200) {
                    editSheepRes(id);
                    layer.msg('删除成功');
                    getListData(1);
                } else {
                    layer.msg('删除失败');
                }
            },
            error: function () {
                layer.msg('删除请求失败');
            }
        });
    }

    // 监听工具条，实现删除功能
    table.on('tool(ID-table-demo-setRowChecked)', function (obj) {
        var data = obj.data;
        var id = data.id
        if (obj.event == 'edit') {
            location.href = '/SeedBirth/SeedBirthEdit?id=' + id;
        }
        if (obj.event == 'delete') {
            layer.confirm('确定删除吗？', function (index) {
                deleteData(data.id); // 传递正确的数据项ID
                layer.close(index);
            });
        }
    });

    function addLink(d) {
        var addLink = d.motherEarHorn;
        if ('' == addLink || null == addLink || undefined == addLink) {
            return '';
        }
        if (addLink.length > 0) {
            return '<a class="layui-table-link" href="javascript:void(0);" lay-event="link">' + d.motherEarHorn + '</a>';
        }
    }

    // 批量删除
    $(".delAll_btn").click(function () {
        var checkStatus = table.checkStatus('ID-table-demo-setRowChecked'),
            data = checkStatus.data,
            id = "";
        if (data.length > 0) {
            for (var i in data) {
                id += data[i].id + ",";
            }
            id = id.substring(0, id.length - 1);
            layer.confirm('确定删除选中的记录？', { icon: 3, title: '提示信息' }, function (index) {
                $.ajax({
                    url: `http://10.31.60.18:8000/ProduceSetRout/api/SeedBirth/BatchRemoveSeedBirth?ids=${id}`,
                    type: 'delete',
                    success: function (data) {
                        if (data.code == 200) {
                            var ids = id.split(',')
                            $.each(ids, function (index, item) {
                                editSheepRes(item)
                            });
                            layer.msg("批量删除成功");
                            getListData(1);
                        } else {
                            layer.msg("批量删除失败");
                        }
                    },
                    error: function () {
                        layer.msg('批量删除请求失败');
                    }
                });
                layer.close(index);
            });
        } else {
            layer.msg("请选择需要删除的记录");
        }
    });

    $('#addRowBtn').on('click', function () {
        location.href = '/SeedBirth/SeedBirthAdd'
    })

    $(function () {
        // 初始化加载数据
        getListData(1);
    })
})

//回显种母分娩数据
function editSheepRes(id) {
    $.ajax({
        type: 'GET',
        url: `http://10.31.60.18:8000/ProduceGetRout/api/SeedBirthRead/GetSeedBirthInfo?id=${id}`, // 根据实际情况修改ControllerName和ActionName
        success: function (response) {
            var res = response.data
            UpdArchives(res)
        },
        error: function (xhr, status, error) {
            // 处理错误响应
            console.error(error);
        }
    })
}

//修改档案数据
function UpdArchives(response) {
    $.ajax({
        url: 'http://10.31.60.18:8000/ArchivesGetRout/api/Archives/ArchivesGetByEarNumberInfo?EarNumber=' + response.motherEarHorn,
        type: 'get',
        dataType: 'json',
        success: function (data) {
            console.log(response)
            var values = {
                id: data.id,
                earNnumber: data.earNnumber,
                electronicEarNumber: data.electronicEarNumber,
                sheepBreed: data.sheepBreed,
                sheepGender: data.sheepGender,
                sheepBir: data.sheepBir,
                presence: data.presence,
                growthStage: data.growthStage,
                sheepType: data.sheepType,
                cottageId: response.transferBuilding,
                field: response.driveField,
                reproductiveState: data.reproductiveState,
                pregnancyTest: data.pregnancyTest,
                statusDays: data.statusDays,
                productionGrade: data.productionGrade,
                salesGrade: data.salesGrade,
                geneticGrade: data.geneticGrade,
                birthWeight: data.birthWeight,
                weaningDate: data.weaningDate,
                fatherEarNumber: data.fatherEarNumber,
                motherEarNumber: data.motherEarNumber,
                dayAge: data.dayAge,
                monthAge: data.monthAge,
                weaningAge: data.weaningAge,
                sheepBir: data.sheepBir,
                archivesRemark: data.archivesRemark,
                archivesPicture: data.archivesPicture,
                placeBirth: data.placeBirth,
                inDate: data.inDate
            }
            Upd(values)
        },
        error: function () {
            // 处理 AJAX 请求失败的情况
            console.error('Failed to fetch data for dropdown.');
        }
    });
}
function Upd(values) {
    console.log(values)
    // 在这里您可以执行其他操作，例如发送到服务器端进行处理
    $.ajax({
        type: 'PUT',
        url: 'http://10.31.60.18:8000/ArchivesSetRout//api/Archives/ArchivesUpdate', // 根据实际情况修改ControllerName和ActionName
        data: JSON.stringify(values),
        contentType: "application/json",
        success: function (response) {
            console.log(response)
        },
        error: function (xhr, status, error) {
            // 处理错误响应
            console.error(error);
        }
    });
}